const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');

// 客户信息接口
// 参数实例:
// {
//     "cust_id": "C2025070400001",
//     "cust_name": "张三",
//     "cust_level": "A",
//     "gender": "男",
//     "birthdate": "1990-01-01",
//     "mobile": "13800138000",
//     "alt_contact": "李四",
//     "email": "zhangsan@example.com",
//     "address": "北京市海淀区",
//     "source": "线上",
//     "notes": "备注"
// }
router.get('/', authenticateToken, async (req, res) => {
    const { cust_name, cust_level, mobile, source } = req.query;
    let sql = 'SELECT * FROM customer';
    if (cust_name) {
        sql += ` WHERE cust_name LIKE '%${cust_name}%'`;
    }
    if (cust_level) {
        sql += ` WHERE cust_level = '${cust_level}'`;
    }
    if (mobile) {
        sql += ` WHERE mobile = '${cryptoHelper.encrypt(mobile)}'`;
    }
    if (source) {
        sql += ` WHERE source = '${source}'`;
    }

    try {
        const [customers] = await db.execute(sql);
        customers.forEach(item => {
            if (item.birthdate) {
                item.birthdate = dayjs(item.birthdate).format('YYYY-MM-DD');
            } else {
                item.birthdate = null;
            }
            item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss');
            item.last_followup = dayjs(item.last_followup).format('YYYY-MM-DD HH:mm:ss');
            item.mobile = cryptoHelper.decrypt(item.mobile).replace(/^(\d{3})\d+(\d{4})$/, '$1****$2');
        });

        await logUserOperation(req, '查询', '获取客户信息', '获取客户信息成功', '成功');
        res.json({
            success: true,
            message: '获取客户信息成功',
            data: customers
        });
    } catch (error) {
        console.error('获取客户信息失败:', error);
        await logUserOperation(req, '查询', '获取客户信息', '获取客户信息失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取客户信息失败'
        });
    }
});

// 添加客户信息接口
// 参数实例: 
// {
//     "cust_name": "张三",
//     "cust_level": "A",
//     "gender": "男",
//     "birthdate": "1990-01-01",
//     "mobile": "13800138000",
//     "alt_contact": "李四",
//     "email": "zhangsan@example.com",
//     "address": "北京市海淀区",
//     "source": "线上",
//     "notes": "备注"
// }
router.put('/add', authenticateToken, async (req, res) => {
    try {
        let { cust_name, cust_level, gender, birthdate, mobile, alt_contact, email, address, source, notes } = req.body;
        // 验证必需字段
        if (!cust_name) {
            return res.status(400).json({
                success: false,
                message: '客户姓名不能为空'
            });
        }
        if (!cust_level) {
            return res.status(400).json({
                success: false,
                message: '客户等级不能为空'
            });
        }
        if (!gender) {
            return res.status(400).json({
                success: false,
                message: '性别不能为空'
            });
        }
        if (!mobile) {
            return res.status(400).json({
                success: false,
                message: '手机号不能为空'
            });
        }
        if (!source) {
            return res.status(400).json({
                success: false,
                message: '来源不能为空'
            });
        }
        // 获取数据库中最大的cust_id
        const [maxCustId] = await db.execute(
            'SELECT MAX(cust_id) AS max_cust_id FROM customer'
        );
        let nextId = 1;
        if (maxCustId[0].max_cust_id) {
            // 提取数字部分并加1
            const currentNumber = parseInt(maxCustId[0].max_cust_id.substring(1));
            nextId = currentNumber + 1;
        }
        let cust_id = generateString('C', nextId, 5);
        let create_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        let last_followup = dayjs().format('YYYY-MM-DD HH:mm:ss');
        let is_public_pool = '否';
        if (birthdate) {
            birthdate = dayjs(birthdate).format('YYYY-MM-DD HH:mm:ss');
        } else {
            birthdate = null;
        }
        let mobile_hash = cryptoHelper.hash(mobile);
        mobile = cryptoHelper.encrypt(mobile);
        const [result] = await db.execute(
            'INSERT INTO customer (cust_id, cust_name, cust_level, gender, birthdate, mobile,mobile_hash, alt_contact, email, address, source, notes, create_time, last_followup, is_public_pool) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [cust_id, cust_name, cust_level, gender, birthdate, mobile, mobile_hash, alt_contact, email, address, source, notes, create_time, last_followup, is_public_pool]
        );
        await logUserOperation(req, '添加', '新增客户信息', '新增客户信息成功', '成功');
        res.json({
            success: true,
            message: '添加客户信息成功',
            data: result
        });
    } catch (error) {
        await logUserOperation(req, '添加', '新增客户信息', '新增客户信息失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '添加客户信息失败',
            error: error.message
        });
    }
});

// 更新客户信息接口
// 参数实例:
// {
//     "cust_id": "C2025070400001",
//     "cust_name": "张三",
//     "cust_level": "A",
//     "gender": "男",
//     "birthdate": "1990-01-01",
router.post('/update', authenticateToken, async (req, res) => {
    try {
        let { cust_id, cust_name, cust_level, gender, birthdate, mobile, alt_contact, email, address, source, notes } = req.body;
        if (!cust_id) {
            return res.status(400).json({
                success: false,
                message: '客户ID不能为空'
            });
        }
        if (!cust_name) {
            return res.status(400).json({
                success: false,
                message: '客户姓名不能为空'
            });
        }
        if (!cust_level) {
            return res.status(400).json({
                success: false,
                message: '客户等级不能为空'
            });
        }
        if (!gender) {
            return res.status(400).json({
                success: false,
                message: '性别不能为空'
            });
        }
        if (!mobile) {
            return res.status(400).json({
                success: false,
                message: '手机号不能为空'
            });
        }
        if (!source) {
            return res.status(400).json({
                success: false,
                message: '来源不能为空'
            });
        }
        let last_followup = dayjs().format('YYYY-MM-DD HH:mm:ss');
        let mobile_hash = cryptoHelper.hash(mobile);
        mobile = cryptoHelper.encrypt(mobile);
        if (birthdate) {
            birthdate = dayjs(birthdate).format('YYYY-MM-DD HH:mm:ss');
        } else {
            birthdate = null;
        }
        const [result] = await db.execute(
            'UPDATE customer SET cust_name = ?, cust_level = ?, gender = ?, birthdate = ?, mobile = ?,mobile_hash = ?, alt_contact = ?, email = ?, address = ?, source = ?, notes = ?, last_followup = ? WHERE cust_id = ?',
            [cust_name, cust_level, gender, birthdate, mobile, mobile_hash, alt_contact, email, address, source, notes, last_followup, cust_id]
        );
        await logUserOperation(req, '更新', '更新客户信息', '更新客户信息成功', '成功');
        res.json({
            success: true,
            message: '更新客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('更新客户信息失败:', error);
        await logUserOperation(req, '更新', '更新客户信息', '更新客户信息失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新客户信息失败',
            error: error.message
        });
    }
})

// 获取修改初始化
router.get('/getUpdateInit', authenticateToken, async (req, res) => {
    try {
        const { cust_id } = req.query;
        console.log('cust_id', cust_id);
        const [result] = await db.execute('SELECT * FROM customer WHERE cust_id = ?', [cust_id]);
        console.log('result', result);

        result.forEach(item => {
            item.mobile = cryptoHelper.decrypt(item.mobile);
        });


        res.json({
            success: true,
            message: '获取客户信息修改初始化成功',
            data: result
        });
        await logUserOperation(req, '查询', '获取客户信息修改初始化', '获取客户信息修改初始化成功', '成功');
    } catch (error) {
        console.error('获取客户信息修改初始化失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户信息修改初始化失败',
            error: error.message
        });
    }
});

// 删除客户信息接口
// 参数实例:
// {
//     "cust_id": "C2025070400001"
// }
router.delete('/delete/:cust_id', authenticateToken, async (req, res) => {
    try {
        const { cust_id } = req.params;
        console.log('传过来了没有', cust_id);

        if (!cust_id) {
            return res.status(400).json({
                success: false,
                message: '客户ID不能为空'
            });
        }
        const [result] = await db.execute(
            'DELETE FROM customer WHERE cust_id = ?',
            [cust_id]
        );
        await logUserOperation(req, '删除', '删除客户信息', '删除客户信息成功', '成功');
        res.json({
            success: true,
            message: '删除客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('删除客户信息失败:', error);
        await logUserOperation(req, '删除', '删除客户信息', '删除客户信息失败', '失败', error.message);
    }
})

// 验证手机号唯一（AES加密版本）
// 新增
// 参数实例:
// {
//     "mobile": "13800138000"
// }
// 修改
// 参数实例:
// {
//     "mobile": "13800138000",
//     "cust_id": "C2025070400001"
// }
router.get('/check-mobile', authenticateToken, async (req, res) => {
    try {
        const { mobile, cust_id } = req.query;

        // 验证手机号格式
        if (!mobile || !/^1[3-9]\d{9}$/.test(mobile)) {
            return res.status(400).json({
                success: false,
                message: '手机号格式不正确'
            });
        }

        // 生成手机号哈希用于唯一性验证
        const mobileHash = cryptoHelper.hash(mobile);
        console.log('mobileHash', mobileHash);


        // 查询数据库
        let sql = 'SELECT cust_id, cust_name FROM customer WHERE mobile_hash = ?';
        const params = [mobileHash];

        if (cust_id) {
            sql += ' AND cust_id != ?';
            params.push(cust_id);
        }

        const [result] = await db.execute(sql, params);


        if (result.length > 0) {
            return res.json({
                success: false,
                message: '手机号已存在',
                existingCustomer: {
                    cust_id: result[0].cust_id,
                    cust_name: result[0].cust_name
                }
            });
        }

        res.json({
            success: true,
            message: '验证手机号唯一成功',
            data: result
        });
    } catch (error) {
        console.error('验证手机号唯一失败:', error);

        // 记录错误日志
        if (req.query.mobile) {
            const mobileHash = cryptoHelper.generatePhoneHash(req.query.mobile);
        }

        res.status(500).json({
            success: false,
            message: '验证手机号唯一失败',
            error: error.message
        });
    }
});



module.exports = router;
